package com.tour.controller.backend;

import com.google.common.collect.Maps;
import com.tour.common.Const;
import com.tour.common.ResponseCode;
import com.tour.common.ServerResponse;
import com.tour.pojo.EasyUIDataGridResult;
import com.tour.pojo.TrDesc;
import com.tour.pojo.TrevalProject;
import com.tour.pojo.User;
import com.tour.service.IFileService;
import com.tour.service.ITrevalProjectService;
import com.tour.service.IUserService;
import com.tour.util.FastDFSClient;
import com.tour.util.JsonUtils;
import com.tour.util.PropertiesUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * Created by fivedeath
 */
@Controller
@RequestMapping("/manage/trevalproject/")
public class TrevalProjectManageController {
	
//	@Value("${IMAGE_SERVER_URL}")
//	private String IMAGE_SERVER_URL;

    @Autowired
    private IUserService iUserService;
    @Autowired
    private ITrevalProjectService iTrevalProjectService;
    @Autowired
    private IFileService iFileService;

    @RequestMapping(value="save.do",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse projectSave(HttpSession session, TrevalProject trevalProject,String trdesc){
            //填充我们增加项目的业务逻辑
    		User user = (User)session.getAttribute(Const.CURRENT_USER);
    		trevalProject.setUserId(user.getUserId());
            return iTrevalProjectService.saveOrUpdateProject(trevalProject, trdesc);
    }
    
    /**
     * 获取项目描述
     * @param session
     * @param trevalProject
     * @param desc
     * @return
     */
    @RequestMapping(value="getDesc/{descId}",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<TrDesc> projectSave(HttpSession session, @PathVariable Long descId){
    	//填充我们增加项目的业务逻辑
    	return iTrevalProjectService.getTrDescById(descId);
    }
    /**
     * 上架
     * @param session
     * @param id
     * @param status
     * @return
     */
    @RequestMapping("reshelf.do")
    @ResponseBody
    public ServerResponse reshelf(HttpSession session, Long id){
    	System.out.println("+++++++++++++++++++++++++="+id);
            return iTrevalProjectService.setStatus(id,1);
    }
    
    /**
     * 下架
     * @param session
     * @param id
     * @param status
     * @return
     */
    @RequestMapping("instock.do")
    @ResponseBody
    public ServerResponse instock(HttpSession session, Long id){
    	System.out.println("+++++++++++++++++++++++++="+id);
    	return iTrevalProjectService.setStatus(id,0);
    }

    @RequestMapping("detail.do")
    @ResponseBody
    public TrevalProject getDetail(HttpSession session,Long id){
            //填充业务
            return iTrevalProjectService.manageProjectDetail(id).getData();
    }
    @RequestMapping("detail/{id}")
    @ResponseBody
    public ServerResponse<TrevalProject> getTrDetail(HttpSession session,@PathVariable Long id){
    	//填充业务
    	return iTrevalProjectService.manageProjectDetail(id);
    }

    @RequestMapping("list.do")
    @ResponseBody
    public EasyUIDataGridResult getList(HttpSession session, @RequestParam(value = "page",defaultValue = "1") int page,@RequestParam(value = "rows",defaultValue = "10") int rows){
    	//填充业务
            return iTrevalProjectService.getProjectList(page,rows);
    }

    @RequestMapping("search.do")
    @ResponseBody
    public ServerResponse projectSearch(HttpSession session,String projectName,Long projectId, @RequestParam(value = "pageNum",defaultValue = "1") int pageNum,@RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
        User user = (User)session.getAttribute(Const.CURRENT_USER);
        if(user == null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(),"用户未登录,请登录管理员");

        }
        if(iUserService.checkAdminRole(user).isSuccess()){
            //填充业务
            return iTrevalProjectService.searchProject(projectName,projectId,pageNum,pageSize);
        }else{
            return ServerResponse.createByErrorMessage("无权限操作");
        }
    }
    
    //查询总数
    @RequestMapping("getTrCount.do")
    @ResponseBody
    public ServerResponse getCount(){
            //填充业务
            return iTrevalProjectService.getTrCount();
    }
    
    //删除
    @RequestMapping("delete.do")
    @ResponseBody
    public ServerResponse delete(Long id){
            //填充业务
            return iTrevalProjectService.deleteProject(id);
    }

    @RequestMapping(value="imgupload.do",produces=MediaType.TEXT_PLAIN_VALUE+";charset=UTF-8")
    @ResponseBody
    public String  upload(HttpSession session,@RequestParam(value = "upload_file",required = false) MultipartFile upload_file,HttpServletRequest request){
    	try {
			//把图片上传的图片服务器
			FastDFSClient fastDFSClient = new FastDFSClient("D:/Program Files/Git/happy_tour/happy_tour Maven Webapp/src/main/resources/conf/img-client.conf");
			//取文件扩展名
			String originalFilename = upload_file.getOriginalFilename();
			System.out.println("==============imgfilename"+originalFilename);
			String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
			//得到一个图片的地址和文件名
			String url = fastDFSClient.uploadFile(upload_file.getBytes(), extName);
			//补充为完整的url
			url = "http://192.168.25.133/" + url;
			//封装到map中返回
			Map result = Maps.newHashMap();
			result.put("error", 0);
			result.put("url", url);
			return JsonUtils.objectToJson(result);
		} catch (Exception e) {
			e.printStackTrace();
			Map result = Maps.newHashMap();
			result.put("error", 1);
			result.put("message", "图片上传失败");
			return JsonUtils.objectToJson(result);
		}
    }
    
    @RequestMapping("richtext_img_upload.do")
    @ResponseBody
    public Map richtextImgUpload(HttpSession session, @RequestParam(value = "upload_file",required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response){
        Map resultMap = Maps.newHashMap();
        User user = (User)session.getAttribute(Const.CURRENT_USER);
        if(user == null){
            resultMap.put("success",false);
            resultMap.put("msg","请登录管理员");
            return resultMap;
        }
        //富文本中对于返回值有自己的要求,我们使用是simditor所以按照simditor的要求进行返回
//        {
//            "success": true/false,
//                "msg": "error message", # optional
//            "file_path": "[real file path]"
//        }
        if(iUserService.checkAdminRole(user).isSuccess()){
            String path = request.getSession().getServletContext().getRealPath("upload");
            String targetFileName = iFileService.upload(file,path);
            if(StringUtils.isBlank(targetFileName)){
                resultMap.put("success",false);
                resultMap.put("msg","上传失败");
                return resultMap;
            }
            String url = PropertiesUtil.getProperty("ftp.server.http.prefix")+targetFileName;
            resultMap.put("success",true);
            resultMap.put("msg","上传成功");
            resultMap.put("file_path",url);
            response.addHeader("Access-Control-Allow-Headers","X-File-Name");
            return resultMap;
        }else{
            resultMap.put("success",false);
            resultMap.put("msg","无权限操作");
            return resultMap;
        }
    }
}
